* Is foreign aid fungible WBER results, Nicolas Van de Sijpe, 04-July-2012


*******************************************************
* SET UP
*******************************************************
capture log close
clear all
set mem 100m
set more off

/* Use the do-file with the macros: */
include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"
/* Include "programmes" do-file. */ 
include "$datadirfung\WBER programmes for replication.do"
/* Start from the "WBER fung data" dataset. */
use "$datadirfung\WBER fung data"


capture log close
log using "$datadirfung\WBER summary statistics.log", replace
***************************************************************************
* SUMMARY STATISTICS FOR SAMPLE USED (TABLE 1 IN PAPER)
***************************************************************************
/* Education model: */
qui xtreg publicexpeducationFADGDP educationIPtotalGDP6 educationSPtotalGDP6 educationTCtotalGDP6 educationONMtotalGDP6 generaltotalGDP6 /// 
supporttoNGOstotalGDP6 othersectoreducGDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP ///
year1991-year2003, fe vce(robust)
su publicexpeducationFADGDP educationtotalGDP6 educationIPtotalGDP6 educationSPtotalGDP6 educationTCtotalGDP6 educationONMtotalGDP6 generaltotalGDP6 /// 
supporttoNGOstotalGDP6 othersectoreducGDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP if e(sample)
sutex publicexpeducationFADGDP educationtotalGDP6 educationIPtotalGDP6 educationSPtotalGDP6 educationTCtotalGDP6 educationONMtotalGDP6 generaltotalGDP6 /// 
supporttoNGOstotalGDP6 othersectoreducGDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP /// 
if e(sample), labels minmax digits(2)
/* Health model: */
qui xtreg publicexphealthFADGDP healthIPtotalGDP6 healthSPtotalGDP6 healthTCtotalGDP6 healthONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
othersectorhealthGDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003, fe vce(robust)
su publicexphealthFADGDP healthtotalGDP6 healthIPtotalGDP6 healthSPtotalGDP6 healthTCtotalGDP6 healthONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
othersectorhealthGDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP if e(sample)
sutex publicexphealthFADGDP healthtotalGDP6 healthIPtotalGDP6 healthSPtotalGDP6 healthTCtotalGDP6 healthONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
othersectorhealthGDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP /// 
if e(sample), labels minmax digits(2)
log close


capture log close
log using "$datadirfung\WBER aggregate vs disaggregate sectoral aid and double log.log", replace
**********************************************************************************
* AGGREGATE VS DISAGGREGATE SECTORAL AID AND DOUBLE LOG
**********************************************************************************
qui {
	qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"
	foreach sector in education health {
		if "`sector'" == "education" {
			local SECTOR EDUCATION
		}
		else if "`sector'" == "health" {
			local SECTOR HEALTH
		}
		
		/* Loop over aggregate and disaggregate models: */
		foreach model in DISAGGR AGGR DISAGGRLN AGGRLN {
			if "`model'" == "DISAGGRLN" | "`model'" == "AGGRLN" {
				local pre ln
			}
			else {
				local pre ""
			}
		
			/* OLS */
			eststo OLS`SECTOR'`model': regress `pre'publicexp`sector'FADGDP ``SECTOR'`model'' year1991-year2003, vce(cluster recipientid)
			fungstoreresults `sector' OLS OLS`SECTOR'`model' ``SECTOR'`model''
			/* FE */
			eststo FE`SECTOR'`model': xtreg `pre'publicexp`sector'FADGDP ``SECTOR'`model'' year1991-year2003, fe vce(cluster recipientid)
			fungstoreresults `sector' FE FE`SECTOR'`model' ``SECTOR'`model''	
		}/* end loop over models */
	}/* end loop over sectors */
}/* end qui */
di "SECTOR: education; MODEL: linear"
esttab OLSEDUCATIONAGGR FEEDUCATIONAGGR OLSEDUCATIONDISAGGR FEEDUCATIONDISAGGR, /// 
keep(`EDUCATIONDISAGGR' `EDUCATIONAGGR') order(`EDUCAGGRDISAGGR') `AGGRDISAGGRStataoutput'
di "SECTOR: health; MODEL: linear"
esttab OLSHEALTHAGGR FEHEALTHAGGR OLSHEALTHDISAGGR FEHEALTHDISAGGR, /// 
keep(`HEALTHDISAGGR' `HEALTHAGGR') order(`HEALTHAGGRDISAGGR') `AGGRDISAGGRStataoutput'
di "SECTOR: education; MODEL: log-linear"
esttab OLSEDUCATIONAGGRLN FEEDUCATIONAGGRLN OLSEDUCATIONDISAGGRLN FEEDUCATIONDISAGGRLN, /// 
keep(`EDUCATIONDISAGGRLN' `EDUCATIONAGGRLN') order(`EDUCAGGRDISAGGRLN') `AGGRDISAGGRLNStataoutput'
di "SECTOR: health; MODEL: log-linear"
esttab OLSHEALTHAGGRLN FEHEALTHAGGRLN OLSHEALTHDISAGGRLN FEHEALTHDISAGGRLN, /// 
keep(`HEALTHDISAGGRLN' `HEALTHAGGRLN') order(`HEALTHAGGRDISAGGRLN') `AGGRDISAGGRLNStataoutput'
drop _est_*
log close // close "WBER aggregate vs disaggregate sectoral aid and double log"


capture log close
log using "$datadirfung\WBER results with CRS aid variables.log", replace
**********************************************************************************
* RESULTS WITH SCALED CRS AID VARIABLES
**********************************************************************************
qui {
	qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"
	foreach sector in education health {
		if "`sector'" == "education" {
			local SECTOR EDUCATION
		}
		else if "`sector'" == "health" {
			local SECTOR HEALTH
		}
		
		/* Loop over aggregate and disaggregate models: */
		foreach model in DISAGGRCRSSC AGGRCRSSC {
		
			/* FE */
			eststo FE`SECTOR'`model': xtreg publicexp`sector'FADGDP ``SECTOR'`model'' year1991-year2003, fe vce(cluster recipientid)
			fungstoreresults `sector' FE FE`SECTOR'`model' ``SECTOR'`model''	

		}/* end loop over models */
	}/* end loop over sectors */
}/* end qui */
di "SECTOR: education; MODEL: CRS scaled"
esttab FEEDUCATIONAGGRCRSSC FEEDUCATIONDISAGGRCRSSC, /// 
keep(`EDUCATIONDISAGGRCRSSC' `EDUCATIONAGGRCRSSC') order(`EDUCAGGRDISAGGRCRSSC') `AGGRDISAGGRStataoutput'
di "SECTOR: health; MODEL: CRS scaled"
esttab FEHEALTHAGGRCRSSC FEHEALTHDISAGGRCRSSC, /// 
keep(`HEALTHDISAGGRCRSSC' `HEALTHAGGRCRSSC') order(`HEALTHAGGRDISAGGRCRSSC') `AGGRDISAGGRStataoutput'
log close // close "WBER results with CRS aid variables.log"


capture log close
log using "$datadirfung\WBER FE change controls.log", replace
************************************************************
* FE regressions, change control variables
************************************************************
gen double ICRG = corruptionICRG + law_orderICRG + burqualICRG
foreach var of varlist ICRG polity polity2 {
	foreach sector in education health {
		if "`sector'" == "education" {
			local SECTOR EDUCATION
		}
		else if "`sector'" == "health" {
			local SECTOR HEALTH
		}

		qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"
		qui xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' `var' year1991-year2003, fe vce(cluster recipientid)
		capture drop sample
		gen sample = 1 if e(sample)

		egen double `var'mean`sector' = mean(`var') if e(sample)
		gen double `var'mzero`sector' = `var' - `var'mean`sector' if e(sample)
		su `var' `var'mean`sector' `var'mzero`sector' if e(sample)

		gen double `sector'SP`var' = `sector'SPtotalGDP6*`var'mzero`sector'
		gen double `sector'TC`var' = `sector'TCtotalGDP6*`var'mzero`sector'
		gen double `sector'IP`var' = `sector'IPtotalGDP6*`var'mzero`sector'
		gen double `sector'ONM`var' = `sector'ONMtotalGDP6*`var'mzero`sector'

	}
}

gen double lnpopulation = ln(population)
foreach var of varlist primaryenrgrossED secondaryenrgrossED infantmort underfivemort {
	gen double L`var' = L.`var'
}
#delimit ;
local EXTRACV `"" " debtpublicLTGDP debtrelief1GDP debtrelief2GDP Ldebtrelief1GDP Ldebtrelief2GDP "only debtrelief1GDP" "only debtrelief2GDP" "log income"
femalelabourforcepart birthrate corruptionICRG law_orderICRG burqualICRG ICRG polity polity2 "drop trade" "drop debt variables" 
"drop trade and debt variables" "ICRG interaction" "polity interaction" "polity2 interaction" "ICRG interaction all" "polity interaction all" 
"polity2 interaction all" shareagrGDP "shareagrGDP no urbanisation" agedependencyratio populationshare0_14 
populationshare65_older "populationshare0_14 and populationshare65_older" lnpopulation primaryenrgrossED secondaryenrgrossED infantmort underfivemort
LprimaryenrgrossED LsecondaryenrgrossED Linfantmort Lunderfivemort"';
#delimit cr
di `"`EXTRACV'"'
 

local counter 0
foreach extravar of local EXTRACV {
	qui {
		qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"

		foreach sector in education health {
			if "`sector'" == "education" {
				local SECTOR EDUCATION
			}
			else if "`sector'" == "health" {
				local SECTOR HEALTH
			}
		
			/* "debtpublicLTGDP": replace debtPVDikhGDP by non-PV measure of debt (debtpublicLTGDP). */
			if "`extravar'" == "debtpublicLTGDP" {
				local olddebt debtPVDikhGDP
				local `SECTOR'DISAGGR: list `SECTOR'DISAGGR - olddebt
				local EDUCHEALTHDISAGGR: list EDUCHEALTHDISAGGR - olddebt
				local cv `extravar'
				local cvreport `extravar'
			}
			/* "only debtrelief1GDP": drop all debt variables and replace by debtrelief1GDP. */
			else if "`extravar'" == "only debtrelief1GDP" {
				local olddebt debtPVDikhGDP debtservicepublicLTGDP
				local `SECTOR'DISAGGR: list `SECTOR'DISAGGR - olddebt
				local EDUCHEALTHDISAGGR: list EDUCHEALTHDISAGGR - olddebt
				local cv debtrelief1GDP
				local cvreport debtrelief1GDP
			}
			/* "only debtrelief2GDP": drop all debt variables and replace by debtrelief2GDP. */
			else if "`extravar'" == "only debtrelief2GDP" {
				local olddebt debtPVDikhGDP debtservicepublicLTGDP
				local `SECTOR'DISAGGR: list `SECTOR'DISAGGR - olddebt
				local EDUCHEALTHDISAGGR: list EDUCHEALTHDISAGGR - olddebt
				local cv debtrelief2GDP
				local cvreport debtrelief2GDP
			}
			/* "log income": replace GDPpercapPPPctthousands by lnGDPpercapitaPPPconstant. */
			else if "`extravar'" == "log income" {
				local old GDPpercapPPPctthousands
				local `SECTOR'DISAGGR: list `SECTOR'DISAGGR - old
				local EDUCHEALTHDISAGGR: list EDUCHEALTHDISAGGR - old
				local cv "lnGDPpercapitaPPPconstant"
				local cvreport "lnGDPpercapitaPPPconstant"
			}
			/* "drop trade": drop tradeGDP. */
			else if "`extravar'" == "drop trade" {
				local oldtrade tradeGDP
				local `SECTOR'DISAGGR: list `SECTOR'DISAGGR - oldtrade
				local EDUCHEALTHDISAGGR: list EDUCHEALTHDISAGGR - oldtrade
				local cv " "
				local cvreport " "
			}
			/* "drop debt variables": drop debtPVDikhGDP and debtservicepublicLTGDP. */
			else if "`extravar'" == "drop debt variables" {
				local olddebt debtPVDikhGDP debtservicepublicLTGDP
				local `SECTOR'DISAGGR: list `SECTOR'DISAGGR - olddebt
				local EDUCHEALTHDISAGGR: list EDUCHEALTHDISAGGR - olddebt
				local cv " "
				local cvreport " "
			}
			/* "drop trade and debt variables": drop tradeGDP, debtPVDikhGDP and debtservicepublicLTGDP. */
			else if "`extravar'" == "drop trade and debt variables" {
				local oldtradedebt tradeGDP debtPVDikhGDP debtservicepublicLTGDP
				local `SECTOR'DISAGGR: list `SECTOR'DISAGGR - oldtradedebt
				local EDUCHEALTHDISAGGR: list EDUCHEALTHDISAGGR - oldtradedebt
				local cv " "
				local cvreport " "
			}
			else if "`extravar'" == "ICRG interaction" {
				local cv ICRGmzero`sector' `sector'SPICRG `sector'TCICRG
				local cvreport ICRGmzeroeducation educationSPICRG educationTCICRG ///
				ICRGmzerohealth healthSPICRG healthTCICRG
			}
			else if "`extravar'" == "polity interaction" {
				local cv politymzero`sector' `sector'SPpolity `sector'TCpolity
				local cvreport politymzeroeducation educationSPpolity educationTCpolity ///
				politymzerohealth healthSPpolity healthTCpolity
			}
			else if "`extravar'" == "polity2 interaction" {
				local cv polity2mzero`sector' `sector'SPpolity2 `sector'TCpolity2
				local cvreport polity2mzeroeducation educationSPpolity2 educationTCpolity2 ///
				polity2mzerohealth healthSPpolity2 healthTCpolity2
			}
			else if "`extravar'" == "ICRG interaction all" {
				local cv ICRGmzero`sector' `sector'IPICRG `sector'SPICRG `sector'TCICRG `sector'ONMICRG
				local cvreport ICRGmzeroeducation educationIPICRG educationSPICRG educationTCICRG educationONMICRG /// 
				ICRGmzerohealth healthIPICRG healthSPICRG healthTCICRG healthONMICRG
			}
			else if "`extravar'" == "polity interaction all" {
				local cv politymzero`sector' `sector'IPpolity `sector'SPpolity `sector'TCpolity `sector'ONMpolity
				local cvreport politymzeroeducation educationIPpolity educationSPpolity educationTCpolity educationONMpolity /// 
				politymzerohealth healthIPpolity healthSPpolity healthTCpolity healthONMpolity
			}
			else if "`extravar'" == "polity2 interaction all" {
				local cv polity2mzero`sector' `sector'IPpolity2 `sector'SPpolity2 `sector'TCpolity2 `sector'ONMpolity2
				local cvreport polity2mzeroeducation educationIPpolity2 educationSPpolity2 educationTCpolity2 educationONMpolity2 /// 
				polity2mzerohealth healthIPpolity2 healthSPpolity2 healthTCpolity2 healthONMpolity2
			}
			/* "shareagrGDP no urbanisation": replace urbanisation by shareagrGDP. */
			else if "`extravar'" == "shareagrGDP no urbanisation" {
				local oldurban urbanisation
				local `SECTOR'DISAGGR: list `SECTOR'DISAGGR - oldurban
				local EDUCHEALTHDISAGGR: list EDUCHEALTHDISAGGR - oldurban
				local cv shareagrGDP
				local cvreport shareagrGDP
			}
			/* "agricempl no urbanisation": replace urbanisation by agricempl. */
			else if "`extravar'" == "agricempl no urbanisation" {
				local oldurban urbanisation
				local `SECTOR'DISAGGR: list `SECTOR'DISAGGR - oldurban
				local EDUCHEALTHDISAGGR: list EDUCHEALTHDISAGGR - oldurban
				local cv agricempl
				local cvreport agricempl
			}
			/* "populationshare0_14 and populationshare65_older". */
			else if "`extravar'" == "populationshare0_14 and populationshare65_older" {
				local cv populationshare0_14 populationshare65_older
				local cvreport populationshare0_14 populationshare65_older
			}
			else { // in all other cases: add the indicated variable as a regressor.
				local cv `extravar'
				local cvreport `extravar'
			}
			
			/* FE */
			eststo FE`SECTOR'DISAGGR`counter': xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' `cv' year1991-year2003, fe vce(cluster recipientid)
			fungstoreresults `sector' FE FE`SECTOR'DISAGGR`counter' ``SECTOR'DISAGGR' `cv'				

		}/* end of foreach loop over the sectors. */
	}/* end of qui */
	di "MODEL WITH `extravar' (NUMBER OF COUNTER: `counter')"
	esttab FEEDUCATIONDISAGGR`counter' FEHEALTHDISAGGR`counter', /// 
	keep(`EDUCATIONDISAGGR' `HEALTHDISAGGR' `cvreport') order(`EDUCHEALTHDISAGGR' `cv') `FEStataoutput'
	local counter = `counter' + 1
}/* end of control variable loop */


/* Results change slightly when some of the control variables are added. 
Is this is due to the effect of the added control variables or due to the change in the sample? */
#delimit ;
local EXTRACV `"birthrate corruptionICRG law_orderICRG burqualICRG ICRG polity polity2"' ;
#delimit cr
di `"`EXTRACV'"'
local counter 0
foreach extravar of local EXTRACV {
	qui {
		qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"

		foreach sector in education health {
			if "`sector'" == "education" {
				local SECTOR EDUCATION
			}
			else if "`sector'" == "health" {
				local SECTOR HEALTH
			}
			local cv `extravar'		
	
			/* FE model with control variable */
			eststo FE`SECTOR'DISAGGR`counter'CV: xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' `cv' year1991-year2003, fe vce(cluster recipientid)
			fungstoreresults `sector' FE FE`SECTOR'DISAGGR`counter'CV ``SECTOR'DISAGGR' `cv'				
			/* FE model without control variable but over same reduced sample */
			qui xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' `cv' year1991-year2003, fe vce(cluster recipientid)
			eststo FE`SECTOR'DISAGGR`counter'noCV: xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003 if e(sample), fe vce(cluster recipientid)
			fungstoreresults `sector' FE FE`SECTOR'DISAGGR`counter'noCV ``SECTOR'DISAGGR' 				

		}/* end loop over sectors */
	}/* end qui */
	di "MODEL WITH `extravar' (NUMBER OF COUNTER: `counter')"
	esttab FEEDUCATIONDISAGGR`counter'CV FEEDUCATIONDISAGGR`counter'noCV FEHEALTHDISAGGR`counter'CV FEHEALTHDISAGGR`counter'noCV, /// 
	keep(`EDUCATIONDISAGGR' `HEALTHDISAGGR' `cv') order(`EDUCHEALTHDISAGGR' `cv') `OLSFEFDStataoutput'
	local counter = `counter' + 1
}/* end control variable loop. */
/* In all cases the change in results is predominantly due to a change in sample rather than the addition of the control variable. */
drop _est_*
log close


capture log close
log using "$datadirfung\WBER vary definition on- and off-budget aid.log", replace
************************************************************
* VARY DEFINITION OF ON- AND OFF-BUDGET AID.
************************************************************
/* Effect total education and health aid under different off-budget scenarios. */
*set trace on
foreach sector in education health {
	if "`sector'" == "education" {
		local sectorshort educ
	}
	else if "`sector'" == "health" {
		local sectorshort health
	}
	else {
		di as error "sector incorrectly specified"
		exit 198
	} // end of if command specifying sector locals
	xtreg publicexp`sector'FADGDP `sector'totalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap /// 
	urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003, fe vce(robust)
	scalar beta_`sectorshort'aid = _b[`sector'totalGDP6]
	scalar se_beta_`sectorshort'aid = _se[`sector'totalGDP6]
	foreach matrix in beta_on_`sectorshort' beta_on_`sectorshort'_se beta_on_`sectorshort'_fullfungp beta_on_`sectorshort'_nofungp { // generate matrices with 0's.
		matrix `matrix' = J(7,7,0)
		matrix colnames `matrix' = -1 -3/4 -1/2 0 1/2 3/4 1
		matrix rownames `matrix' = 1/4 1/2 3/4 1 3/2 2 4
	} // end generation matrices
	qui {
		local i = 0
		foreach relvar_off_vs_on of numlist 0.25 0.5 0.75 1 1.5 2 4 { // vary relative variance of off-budget versus on-budget aid.
			local++i
			local relstdev_off_vs_on = sqrt(`relvar_off_vs_on')
			local j = 0
			foreach corr_on_off of numlist -1 -0.75 -0.5 0 0.5 0.75 1 { // vary correlation between on- and off-budget aid.
				local ++j
				scalar entry`i'`j'_beta_`sectorshort' = beta_`sectorshort'aid + 1 - ((1 + `corr_on_off' * `relstdev_off_vs_on')/(1 + `relstdev_off_vs_on'^2 + 2 * `corr_on_off' * `relstdev_off_vs_on')) // coefficient
				scalar entry`i'`j'_se_`sectorshort' = se_beta_`sectorshort'aid // standard error is just the standard error of the coefficient in the original regression.
				test _b[`sector'totalGDP6] = 0
				scalar fullfungtest`i'`j'_`sectorshort' = ttail(r(df_r), entry`i'`j'_beta_`sectorshort'/entry`i'`j'_se_`sectorshort') // full fungibility test p-value
				test _b[`sector'totalGDP6] = 1
				scalar nofungtest`i'`j'_`sectorshort' = ttail(r(df_r), - (entry`i'`j'_beta_`sectorshort'-1)/entry`i'`j'_se_`sectorshort') // no fungibility test p-value
				/* Build up the matrices. */
				mat beta_on_`sectorshort'[`i',`j'] = entry`i'`j'_beta_`sectorshort' // matrix with coefficients
				mat beta_on_`sectorshort'_se[`i',`j'] = entry`i'`j'_se_`sectorshort' // matrix with standard errors
				mat beta_on_`sectorshort'_fullfungp[`i',`j'] = fullfungtest`i'`j'_`sectorshort' // matrix with p-values full fungibility test
				mat beta_on_`sectorshort'_nofungp[`i',`j'] = nofungtest`i'`j'_`sectorshort' // matrix with p-values full fungibility test
			}/* end loop over corr_on_off*/
		}/* end loop over relstdev_off_vs_on */
	}/* end qui */
	matrix list beta_on_`sectorshort'
	matrix list beta_on_`sectorshort'_se
	matrix list beta_on_`sectorshort'_fullfungp
	matrix list beta_on_`sectorshort'_nofungp
}/* end loop over sectors. */


/* Effect disaggregated education and health aid pieces under different off-budget scenarios. */
*set trace on
foreach sector in education health {
	if "`sector'" == "education" {
		local sectorshort educ
	}
	else if "`sector'" == "health" {
		local sectorshort health
	}
	else {
		di as error "sector incorrectly specified"
		exit 198
	} // end of if command specifying sector locals

	foreach type in IP SP TC ONM {
		if "`type'" == "IP" | "`type'" == "ONM" {
			foreach matrix in beta_on_`sectorshort'`type' beta_on_`sectorshort'`type'_se beta_on_`sectorshort'`type'_fullfungp /// 
			beta_on_`sectorshort'`type'_nofungp { // generate matrices with 0's
				matrix `matrix' = J(7,7,0)
				matrix colnames `matrix' = -1 -3/4 -1/2 0 1/2 3/4 1
				matrix rownames `matrix' = 1/4 1/2 3/4 1 3/2 2 4
			} // end generation IP and ONM matrices
			local relvar_off_vs_on`type' 0.25 0.5 0.75 1 1.5 2 4
		}
		else if "`type'" == "SP" {
			foreach matrix in beta_on_`sectorshort'`type' beta_on_`sectorshort'`type'_se beta_on_`sectorshort'`type'_fullfungp /// 
			beta_on_`sectorshort'`type'_nofungp { // generate matrices with 0's
				matrix `matrix' = J(4,7,0)
				matrix colnames `matrix' = -1 -3/4 -1/2 0 1/2 3/4 1
				matrix rownames `matrix' = 1/4 1/2 3/4 1
			} // end generation SP matrices		
			local relvar_off_vs_on`type' 0.25 0.5 0.75 1
		}
		else if "`type'" == "TC" {
			foreach matrix in beta_on_`sectorshort'`type' beta_on_`sectorshort'`type'_se beta_on_`sectorshort'`type'_fullfungp /// 
			beta_on_`sectorshort'`type'_nofungp { // generate matrices with 0's
				matrix `matrix' = J(4,7,0)
				matrix colnames `matrix' = -1 -3/4 -1/2 0 1/2 3/4 1
				matrix rownames `matrix' = 1 3/2 2 4
			} // end generation TC matrices
			local relvar_off_vs_on`type' 1 1.5 2 4
		}
		else {
			di as error "aid type incorrectly specified"
			exit 198
		} // end if command specifying aid types
	
		xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'SPtotalGDP6 `sector'TCtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 /// 
		supporttoNGOstotalGDP6 othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP ///
		year1991-year2003, fe vce(robust)
		scalar beta_`sectorshort'`type' = _b[`sector'`type'totalGDP6]
		scalar se_beta_`sectorshort'`type' = _se[`sector'`type'totalGDP6]
		
		qui {
			local i = 0
			foreach relvar_off_vs_on of local relvar_off_vs_on`type' { // vary relative variance of off-budget versus on-budget aid. Numbers used depend on aid type (see above).
				local++i
				local relstdev_off_vs_on = sqrt(`relvar_off_vs_on')
				local j = 0
				foreach corr_on_off of numlist -1 -0.75 -0.5 0 0.5 0.75 1 { // vary correlation between on- and off-budget aid.
					local ++j
					scalar entry`i'`j'_beta_`sectorshort'`type' = beta_`sectorshort'`type' + 1 - ((1 + `corr_on_off' * `relstdev_off_vs_on')/(1 + `relstdev_off_vs_on'^2 + 2 * `corr_on_off' * `relstdev_off_vs_on')) // coefficient
					scalar entry`i'`j'_se_`sectorshort'`type' = se_beta_`sectorshort'`type' // standard error
					test _b[`sector'`type'totalGDP6] = 0
					scalar fullfungtest`i'`j'_`sectorshort'`type' = ttail(r(df_r), entry`i'`j'_beta_`sectorshort'`type'/entry`i'`j'_se_`sectorshort'`type') // full fungibility test p-value
					test _b[`sector'`type'totalGDP6] = 1
					scalar nofungtest`i'`j'_`sectorshort'`type' = ttail(r(df_r), - (entry`i'`j'_beta_`sectorshort'`type'-1)/entry`i'`j'_se_`sectorshort'`type') // no fungibility test p-value
					/* Build up the matrices. */
					mat beta_on_`sectorshort'`type'[`i',`j'] = entry`i'`j'_beta_`sectorshort'`type' // matrix with coefficients
					mat beta_on_`sectorshort'`type'_se[`i',`j'] = entry`i'`j'_se_`sectorshort'`type' // matrix with standard errors
					mat beta_on_`sectorshort'`type'_fullfungp[`i',`j'] = fullfungtest`i'`j'_`sectorshort'`type' // matrix with p-values full fungibility test
					mat beta_on_`sectorshort'`type'_nofungp[`i',`j'] = nofungtest`i'`j'_`sectorshort'`type' // matrix with p-values full fungibility test
				}/* end loop over corr_on_off*/
			}/* end loop over relstdev_off_vs_on */
		}/* end qui */
		matrix list beta_on_`sectorshort'`type'
		matrix list beta_on_`sectorshort'`type'_se
		matrix list beta_on_`sectorshort'`type'_fullfungp
		matrix list beta_on_`sectorshort'`type'_nofungp
	} // end loop over types.
} // end loop over sectors.


/* In the panel data model with control variables, what is the relative variance and correlation between the different aid types? */
foreach sector in education health {
	if "`sector'" == "education" {
		local sectorshort educ
	}
	else if "`sector'" == "health" {
		local sectorshort health
	}
	else {
		di as error "sector incorrectly specified"
		exit 198
	} // end of if command specifying sector locals

	xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'SPtotalGDP6 `sector'TCtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 ///
	othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003, fe vce(robust)
	capture drop `sectorshort'sample
	gen `sectorshort'sample = 1 if e(sample)

	foreach type in IP SP TC ONM {
		xtreg `sector'`type'totalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation /// 
		tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003 if `sectorshort'sample == 1, fe vce(robust)
		predict within_`sectorshort'`type'_res, e
	} // end loop over aid types

	xtreg publicexp`sector'FADGDP generaltotalGDP6 supporttoNGOstotalGDP6 othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap /// 
	urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003 if `sectorshort'sample == 1, fe vce(robust)
	predict within_`sectorshort'exp_res, e

	/* Check partialled out regression works: */
	xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'SPtotalGDP6 `sector'TCtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
	othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003, fe vce(robust)
	reg within_`sectorshort'exp_res within_`sectorshort'IP_res within_`sectorshort'SP_res within_`sectorshort'TC_res within_`sectorshort'ONM_res, nocons
	/* So what do the variances and correlations look like? */
	di "`sector'"
	su within_`sectorshort'exp_res within_`sectorshort'IP_res within_`sectorshort'SP_res within_`sectorshort'TC_res within_`sectorshort'ONM_res
	pwcorr within_`sectorshort'IP_res within_`sectorshort'SP_res within_`sectorshort'TC_res within_`sectorshort'ONM_res
} // end loop over the two sectors
log close


log using "$datadirfung\WBER DFBETA creation.log", replace
************************************************
* CREATE DFBETAS
************************************************
qui {
	qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"
	foreach sector in education health {
		if "`sector'" == "education" {
			local SECTOR EDUCATION
		}
		else if "`sector'" == "health" {
			local SECTOR HEALTH
		}
		
		xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003, fe vce(cluster recipientid)
		capture drop `sector'sample
		gen `sector'sample=1==e(sample)
		count if `sector'sample == 1
		assert r(N) == e(N) // Check the count of `sector'sample equals the number of observations from the last estimated model.
		
		/* Save standard errors and coefficients from original model: */
		scalar `sector'seSPorig = _se[`sector'SPtotalGDP6]
		scalar `sector'seTCorig = _se[`sector'TCtotalGDP6]
		scalar coeff`sector'SPorig = _b[`sector'SPtotalGDP6]
		scalar coeff`sector'TCorig = _b[`sector'TCtotalGDP6]
		*display `sector'seSPorig `sector'seTCorig coeff`sector'SPorig coeff`sector'TCorig
		/* Generate variables in which to store coefficients. */
		foreach var of newlist coeff`sector'SP coeff`sector'TC `sector'seSP `sector'seTC pvalues`sector'SP pvalues`sector'TC {
			gen double `var' = .
		}/* end newlist loop */
		qui su recipientid
		local countries = r(max)
		foreach id of numlist 1/`countries' {
			qui xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003 if recipientid != `id' & `sector'sample == 1, fe vce(cluster recipientid)
			foreach type in SP TC {
				qui replace coeff`sector'`type' = _b[`sector'`type'totalGDP6] if recipientid == `id' & `sector'sample == 1
				qui replace `sector'se`type' = _se[`sector'`type'totalGDP6] if recipientid == `id' & `sector'sample == 1
				qui replace pvalues`sector'`type' = 2*ttail(e(df_r),abs(_b[`sector'`type'totalGDP6]/_se[`sector'`type'totalGDP6])) /// 
				if recipientid == `id' & `sector'sample == 1
			}/* end loop over types */
		}/* end loop over countries */
		foreach var of varlist coeff`sector'SP coeff`sector'TC `sector'seSP `sector'seTC pvalues`sector'SP pvalues`sector'TC {
			by recipientid: egen `var'mean = mean(`var')
			drop `var'
			rename `var'mean `var'
		}
		/* The six created variables now show up for every year for those countries that are included in the original regression.
		For countries that were not part of the original regression these six variables are missing, which is how it should be. */
		/* Generate dfbetas */
		gen double dfbeta`sector'SP = (coeff`sector'SP - coeff`sector'SPorig)/`sector'seSP
		gen double dfbeta`sector'TC = (coeff`sector'TC - coeff`sector'TCorig)/`sector'seTC
	}/* end sector loop */
}/* end qui */
log close


capture log close
log using "$datadirfung\WBER DFBETA analysis.log", replace
*************************************
* ANALYSIS OF THE DFBETAS
*************************************
qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"
qui include "$datadirfung\WBER programmes for replication.do"
qui {
	foreach sector in education health {
		local counter = 1 // defines the model with SP outliers dropped, TC outliers dropped, or both outliers dropped 
		if "`sector'" == "education" {
			local SECTOR EDUCATION
			local Sector Education
		}
		else if "`sector'" == "health" {
			local SECTOR HEALTH
			local Sector Health
		}

		xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003, fe vce(cluster recipientid)
		local Ncountries = e(N_clust)
		di "`Ncountries'"
		su dfbeta`sector'SP dfbeta`sector'TC coeff`sector'SP coeff`sector'TC pvalues`sector'SP pvalues`sector'TC if year == 1990, detail
		/* Most stringent cut-off point: 2/sqrt(Ncountries) */
		foreach type in SP TC {
			count if abs(dfbeta`sector'`type') > 2/sqrt(`Ncountries') & dfbeta`sector'`type' != . & year == 1990
			local count = `Ncountries' - r(N)
			di "Number of countries with dfbeta`sector'`type' above cut-off: " r(N)
			list recipient year coeff`sector'`type' pvalues`sector'`type' dfbeta`sector'`type' /// 
			if abs(dfbeta`sector'`type') > 2/sqrt(`Ncountries') & dfbeta`sector'`type' != . & year == 1990
	
			hist coeff`sector'`type' if year == 1990, freq xtitle(`Sector' `type')
			hist pvalues`sector'`type' if year == 1990, freq xtitle(`Sector' `type' p-values)
		
			di "MODEL WITH dfbeta`sector'`type' DROPPED:"
			eststo FE`SECTOR'DISAGGR`counter': xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003 /// 
			if abs(dfbeta`sector'`type') < 2/sqrt(`Ncountries'), fe vce(cluster recipientid)
			qui fungstoreresults `sector' FE FE`SECTOR'DISAGGR`counter++' ``SECTOR'DISAGGR'
		}/* end loop over types. */
		count if abs(dfbeta`sector'SP) < 2/sqrt(`Ncountries') & abs(dfbeta`sector'TC) < 2/sqrt(`Ncountries') & year == 1990
		local count = `Ncountries' - r(N)		
		di "Number of countries with dfbeta`sector'SP or dfbeta`sector'TC above cut-off: " `count'
		list recipient year if /// 
		((abs(dfbeta`sector'SP) > 2/sqrt(`Ncountries') & dfbeta`sector'SP != .) | (abs(dfbeta`sector'TC) > 2/sqrt(`Ncountries') & dfbeta`sector'TC != .)) /// 
		& year == 1990
		di "DISAGGREGATED MODEL WITH dfbeta`sector'SP and dfbeta`sector'TC DROPPED (`count' COUNTRIES DROPPED):"
		/* FE MODEL */
		eststo FE`SECTOR'DISAGGR`counter': xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003 /// 
		if abs(dfbeta`sector'SP) < 2/sqrt(`Ncountries') & abs(dfbeta`sector'TC) < 2/sqrt(`Ncountries'), fe vce(cluster recipientid)
		qui fungstoreresults `sector' FE FE`SECTOR'DISAGGR`counter' ``SECTOR'DISAGGR'
		/* FD MODEL */
		preserve
		foreach var in publicexp`sector'FADGDP ``SECTOR'DISAGGR' { 
			qui gen double D`var' = D.`var'
			qui replace `var' = D`var'
		}
		eststo FD`SECTOR'DISAGGR`counter': regress publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003 /// 
		if abs(dfbeta`sector'SP) < 2/sqrt(`Ncountries') & abs(dfbeta`sector'TC) < 2/sqrt(`Ncountries'), vce(cluster recipientid)
		qui fungstoreresults `sector' FD FD`SECTOR'DISAGGR`counter' ``SECTOR'DISAGGR'
		capture restore

		di "AGGREGATE MODEL WITH dfbeta`sector'SP and dfbeta`sector'TC DROPPED (`count' COUNTRIES DROPPED):"
		eststo FE`SECTOR'AGGR: xtreg publicexp`sector'FADGDP ``SECTOR'AGGR' year1991-year2003 /// 
		if abs(dfbeta`sector'SP) < 2/sqrt(`Ncountries') & abs(dfbeta`sector'TC) < 2/sqrt(`Ncountries'), fe vce(cluster recipientid)
		qui fungstoreresults `sector' FE FE`SECTOR'AGGR ``SECTOR'AGGR'
		/* FD model */
		preserve
		foreach var in publicexp`sector'FADGDP ``SECTOR'AGGR' { 
			qui gen double D`var' = D.`var'
			qui replace `var' = D`var'
		}
		eststo FD`SECTOR'AGGR: regress publicexp`sector'FADGDP ``SECTOR'AGGR' year1991-year2003 /// 
		if abs(dfbeta`sector'SP) < 2/sqrt(`Ncountries') & abs(dfbeta`sector'TC) < 2/sqrt(`Ncountries'), vce(cluster recipientid)
		qui fungstoreresults `sector' FD FD`SECTOR'AGGR ``SECTOR'AGGR'
		capture restore
	}/* end loop over sectors. */
}/* end qui */
/* EDUCATION */
esttab FEEDUCATIONDISAGGR1 FEEDUCATIONDISAGGR2 FEEDUCATIONDISAGGR3 FEEDUCATIONAGGR, /// 
keep(`EDUCATIONDISAGGR' `EDUCATIONAGGR') order(`EDUCAGGRDISAGGR') `OLSFEFDStataoutput' ///
mtitles("dfbeta SP" "dfbeta TC" "dfbeta SP + TC" "dfbeta SP + TC")
esttab FDEDUCATIONDISAGGR3 FDEDUCATIONAGGR, /// 
keep(`EDUCATIONDISAGGR' `EDUCATIONAGGR') order(`EDUCAGGRDISAGGR') `OLSFEFDStataoutput' ///
mtitles("dfbeta SP" "dfbeta TC" "dfbeta SP + TC" "dfbeta SP + TC")
/* HEALTH */
esttab FEHEALTHDISAGGR1 FEHEALTHDISAGGR2 FEHEALTHDISAGGR3 FEHEALTHAGGR, /// 
keep(`HEALTHDISAGGR' `HEALTHAGGR') order(`HEALTHAGGRDISAGGR') `OLSFEFDStataoutput' ///
mtitles("dfbeta SP" "dfbeta TC" "dfbeta SP + TC" "dfbeta SP + TC")
esttab FDHEALTHDISAGGR3 FDHEALTHAGGR, /// 
keep(`HEALTHDISAGGR' `HEALTHAGGR') order(`HEALTHAGGRDISAGGR') `OLSFEFDStataoutput' ///
mtitles("dfbeta SP" "dfbeta TC" "dfbeta SP + TC" "dfbeta SP + TC")


/* Try to construct graphs that show the partial plots in full and reduced sample. */
foreach sector in education health {
	if "`sector'" == "education" {
		local sectorshort educ
	}
	else if "`sector'" == "health" {
		local sectorshort health
	}
	else {
		di as error "sector incorrectly specified"
		exit 198
	} // end of if command specifying sector locals

	xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003, fe vce(cluster recipientid)
	scalar Ncountries`sector' = e(N_clust)
	di "Ncountries`sector'"
	
	foreach sample in FS RS { // loop over full sample and reduced sample.
		if "`sample'" == "FS" {
			local if`sector' ""
		}
		else if "`sample'" == "RS" {
			local if`sector' "if abs(dfbeta`sector'SP) < 2/sqrt(Ncountries`sector') & abs(dfbeta`sector'TC) < 2/sqrt(Ncountries`sector')"
		}
		else {
			di as error "Sample choice not correct"
			exit 198
		}
		
		xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'SPtotalGDP6 `sector'TCtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
		othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003 `if`sector'', fe vce(robust)
		capture drop `sectorshort'sample
		gen `sectorshort'sample = 1 if e(sample) // fix estimation sample
			
		xtreg `sector'SPtotalGDP6 `sector'IPtotalGDP6 `sector'TCtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 othersector`sectorshort'GDP6 /// 
		GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003 /// 
		if `sectorshort'sample == 1, fe vce(robust)
		capture drop within_`sectorshort'SP_res`sample'
		predict within_`sectorshort'SP_res`sample', e

		xtreg `sector'TCtotalGDP6 `sector'IPtotalGDP6 `sector'SPtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 othersector`sectorshort'GDP6 /// 
		GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003 /// 
		if `sectorshort'sample == 1, fe vce(robust)
		capture drop within_`sectorshort'TC_res`sample'
		predict within_`sectorshort'TC_res`sample', e

		xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'TCtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
		othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP /// 
		year1991-year2003 if `sectorshort'sample == 1, fe vce(robust)
		capture drop within_`sectorshort'expSP_res`sample'
		predict within_`sectorshort'expSP_res`sample', e

		xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'SPtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
		othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP /// 
		year1991-year2003 if `sectorshort'sample == 1, fe vce(robust)
		capture drop within_`sectorshort'expTC_res`sample'
		predict within_`sectorshort'expTC_res`sample', e

		/* Check that partialled out regressions work: */
		xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'SPtotalGDP6 `sector'TCtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
		othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003 `if`sector'', fe vce(robust)
		reg within_`sectorshort'expSP_res`sample' within_`sectorshort'SP_res`sample', nocons
		predict `sectorshort'expSP_`sample'
		reg within_`sectorshort'expTC_res`sample' within_`sectorshort'TC_res`sample', nocons
		predict `sectorshort'expTC_`sample'
	} // end loop over full sample and reduced sample
} // end loop over the two sectors
/* Construct and export the graphs. */
graph twoway (scatter within_educexpSP_resRS within_educSP_resRS, ytitle("Public education expenditure") xtitle("Education SP aid") c(i) msymbol(o) mcolor(black)) /// 
(scatter within_educexpSP_resFS within_educSP_resFS if abs(dfbetaeducationSP) > 2/sqrt(Ncountrieseducation) & abs(dfbetaeducationTC) < 2/sqrt(Ncountrieseducation) , c(i) msymbol(plus) mcolor(black)) /// 
(line educexpSP_RS within_educSP_resRS, lpattern(dot) lcolor(black)) (line educexpSP_FS within_educSP_resFS, lpattern(solid) lcolor(black)) ///
, legend(off)

graph twoway (scatter within_educexpTC_resRS within_educTC_resRS if within_educTC_resRS < 4, ytitle("Public education expenditure") xtitle("Education TC") c(i) msymbol(o) mcolor(black)) /// 
(scatter within_educexpTC_resFS within_educTC_resFS if abs(dfbetaeducationSP) > 2/sqrt(Ncountrieseducation) & abs(dfbetaeducationTC) < 2/sqrt(Ncountrieseducation), c(i) msymbol(plus) mcolor(black)) /// 
(line educexpTC_RS within_educTC_resRS if within_educTC_resRS < 4, lpattern(dot) lcolor(black)) (line educexpTC_FS within_educTC_resFS if within_educTC_resRS < 4, lpattern(solid) lcolor(black)) ///
, legend(off)

graph twoway (scatter within_healthexpSP_resRS within_healthSP_resRS if within_healthSP_resRS < 0.5, ytitle("Public health expenditure") xtitle("Health SP aid") c(i) msymbol(o) mcolor(black)) /// 
(scatter within_healthexpSP_resFS within_healthSP_resFS if abs(dfbetahealthSP) > 2/sqrt(Ncountrieshealth) & abs(dfbetahealthTC) < 2/sqrt(Ncountrieshealth), c(i) msymbol(plus) mcolor(black)) /// 
(line healthexpSP_RS within_healthSP_resRS if within_healthSP_resRS < 0.5, lpattern(dot) lcolor(black)) (line healthexpSP_FS within_healthSP_resFS if within_healthSP_resRS < 0.5, lpattern(solid) lcolor(black)) ///
, legend(off)

graph twoway (scatter within_healthexpTC_resRS within_healthTC_resRS if within_healthTC_resRS < 0.62, ytitle("Public health expenditure") xtitle("Health TC") c(i) msymbol(o) mcolor(black)) /// 
(scatter within_healthexpTC_resFS within_healthTC_resFS if abs(dfbetahealthSP) > 2/sqrt(Ncountrieshealth) & abs(dfbetahealthTC) < 2/sqrt(Ncountrieshealth) , c(i) msymbol(plus) mcolor(black)) /// 
(line healthexpTC_RS within_healthTC_resRS if within_healthTC_resRS < 0.62, lpattern(dot) lcolor(black)) (line healthexpTC_FS within_healthTC_resFS if within_healthTC_resRS < 0.62, lpattern(solid) lcolor(black)) ///
, legend(off)
log close // close log WBER DFBETA analysis.log


/* Keep only the generated dfbetas, drop all other newly generated variables (coefficients and p-values) */
foreach sector in education health {
	drop `sector'sample coeff`sector'SP coeff`sector'TC `sector'seSP `sector'seTC pvalues`sector'SP pvalues`sector'TC
}
drop _est_*


/* Save data as "2 DFBETA end" */
save "$datadirfung\WBER DFBETA end", replace


*******************************************************
* START AGAIN FROM WBER DFBETA END DATASET
*******************************************************
capture log close
clear all
set mem 100m
set more off
eststo drop *

/* Use the do-file with the macros: */
include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"
/* Include "programmes" do-file. */ 
include "$datadirfung\WBER programmes for replication.do"
/* Start from the "WBER fung data" dataset. */
use "$datadirfung\WBER DFBETA end"

foreach sector in education health {
		if "`sector'" == "education" {
			local SECTOR EDUCATION
		}
		else if "`sector'" == "health" {
			local SECTOR HEALTH
		}

	xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003, fe vce(cluster recipientid)
	local Ncountries`sector' = e(N_clust)
	di "`Ncountries`sector''"
	
	local reducedsample`sector' "abs(dfbeta`sector'SP) < 2/sqrt(`Ncountries`sector'') & abs(dfbeta`sector'TC) < 2/sqrt(`Ncountries`sector'')" // specify if constraint by sector
}


capture log close
log using "$datadirfung\WBER system GMM reduced dfbeta sample.log", replace
*************************************************************************************************************************
* SYSTEM GMM REDUCED DFBETA SAMPLE
*************************************************************************************************************************
foreach sector in education health {
	if "`sector'" == "education" {
		local Sector Education
	}
	else if "`sector'" == "health" {
		local Sector Health
	}
	foreach var in publicexp`sector'FADGDP {
		capture drop L`var'
		gen double L`var' = L.`var'
	}
	label variable Lpublicexp`sector'FADGDP "Public `sector' exp. lag"
}
*qui {
	qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"

	foreach sector in education health {
		if "`sector'" == "education" {
			local SECTOR EDUCATION
		}
		else if "`sector'" == "health" {
			local SECTOR HEALTH
		}
		else {
			di as error "sector incorrectly specified"
			exit 198
		} // end of if command specifying sector locals

		/* Only look at disaggregate models: */
		foreach model in DISAGGR {
		
			qui xtreg publicexp`sector'FADGDP ``SECTOR'`model'ENDOG' ``SECTOR'PREDETERM' ``SECTOR'STRICTEXOG' `TIME', fe vce(cluster recipientid)
			local Ncountries`sector' =  e(N_clust) // Run a static model to determine N

			foreach instr in 1 2 3 4 { // options: 1 2 3 4
				if "`instr'" == "A" {
					local instrendog "."
					local instrpredeterm "."
				}
				else {
					local instrendog = `instr' + 1
					local instrpredeterm `instr'
				}

				eststo GMML`SECTOR'`model'`instr': xtabond2 publicexp`sector'FADGDP `LAG`SECTOR'' ``SECTOR'`model'ENDOG' /// 
				``SECTOR'PREDETERM' ``SECTOR'STRICTEXOG' `TIME' if `reducedsample`sector'', /// 
				twostep robust small gmmstyle(publicexp`sector'FADGDP, laglimits(2 `instrendog') collapse split) /// 
				gmmstyle(``SECTOR'`model'ENDOG', laglimits(2 `instrendog') collapse) ///
				gmmstyle(``SECTOR'PREDETERM', laglimits(1 `instrpredeterm') collapse) /// 
				ivstyle(``SECTOR'STRICTEXOG' `TIME', eq(level))
				scalar hansendf = e(hansen_df)
				scalar hansenj = e(hansen)
				scalar sarganp = e(sarganp)
				qui fungstoreresults `sector' GMM GMML`SECTOR'`model'`instr' `LAG`SECTOR'' ``SECTOR'`model'ENDOG' ``SECTOR'PREDETERM' /// 
				``SECTOR'STRICTEXOG'
			} // end of loop over different instrument lag lengths.
			di "REDUCED SAMPLE; SECTOR: `SECTOR'; TYPE OF MODEL: "
			esttab GMML`SECTOR'`model'1 GMML`SECTOR'`model'2 GMML`SECTOR'`model'3 GMML`SECTOR'`model'4, /// 
			keep(`LAG`SECTOR'' ``SECTOR'`model'ENDOG' ``SECTOR'PREDETERM' ``SECTOR'STRICTEXOG') order(`L`SECTOR'`model'') `GMMdynamicStataoutput`model''
		} // end of loop over aggregate and disaggregated model.
	} // end of foreach loop over the sectors.
*} // end of qui.
log close


capture log close
log using "$datadirfung\WBER system GMM extra lag reduced dfbeta sample.log", replace
*************************************************************************************************************************
* SYSTEM GMM REDUCED SAMPLE EXTRA AID LAG ADDED
*************************************************************************************************************************
foreach sector in education health {
	if "`sector'" == "education" {
		local Sector Education
	}
	else if "`sector'" == "health" {
		local Sector Health
	}
	foreach var in publicexp`sector'FADGDP `sector'TCtotalGDP6 {
		capture drop L`var'
		gen double L`var' = L.`var'
	}
	label variable Lpublicexp`sector'FADGDP "Public `sector' exp. lag"
	label variable L`sector'TCtotalGDP6 "`Sector' TC lag"
}
*qui {
	qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"

	foreach sector in education health {
		if "`sector'" == "education" {
			local SECTOR EDUCATION
		}
		else if "`sector'" == "health" {
			local SECTOR HEALTH
		}
		else {
			di as error "sector incorrectly specified"
			exit 198
		} // end of if command specifying sector locals

		/* Only look at disaggregate models: */
		foreach model in DISAGGR {
			if "`model'" == "DISAGGR" {
				local extralag L`sector'TCtotalGDP6
			}
			else if "`model'" == "AGGR" {
				local extralag L`sector'totalGDP6
			}
			else {
				di as error "Incorrectly specified model (aggregate versus disaggregate)"
			}
			
			qui xtreg publicexp`sector'FADGDP ``SECTOR'`model'ENDOG' ``SECTOR'PREDETERM' ``SECTOR'STRICTEXOG' `TIME', fe vce(cluster recipientid)
			local Ncountries`sector' =  e(N_clust) // Run a static model to determine N

			foreach instr in 1 2 3 4 {
				if "`instr'" == "A" {
					local instrendog "."
					local instrpredeterm "."
				}
				else {
					local instrendog = `instr' + 1
					local instrpredeterm `instr'
				}

				eststo GMML`SECTOR'`model'`instr': xtabond2 publicexp`sector'FADGDP `LAG`SECTOR'' `extralag' ``SECTOR'`model'ENDOG' /// 
				``SECTOR'PREDETERM' ``SECTOR'STRICTEXOG' `TIME' if `reducedsample`sector'', /// 
				twostep robust small gmmstyle(publicexp`sector'FADGDP, laglimits(2 `instrendog') collapse split) /// 
				gmmstyle(``SECTOR'`model'ENDOG', laglimits(2 `instrendog') collapse) ///
				gmmstyle(``SECTOR'PREDETERM', laglimits(1 `instrpredeterm') collapse) /// 
				ivstyle(``SECTOR'STRICTEXOG' `TIME', eq(level))
				scalar hansendf = e(hansen_df)
				scalar hansenj = e(hansen)
				scalar sarganp = e(sarganp)
				qui fungstoreresults `sector' GMM GMML`SECTOR'`model'`instr' `LAG`SECTOR'' `extralag' ``SECTOR'`model'ENDOG' ``SECTOR'PREDETERM' /// 
				``SECTOR'STRICTEXOG'
			} // end of loop over different instrument lag lengths.
			di "REDUCED SAMPLE; SECTOR: `SECTOR'; TYPE OF MODEL: "
			esttab GMML`SECTOR'`model'1 GMML`SECTOR'`model'2 GMML`SECTOR'`model'3 GMML`SECTOR'`model'4, /// 
			keep(`LAG`SECTOR'' `extralag' ``SECTOR'`model'ENDOG' ``SECTOR'PREDETERM' ``SECTOR'STRICTEXOG') order(`L`SECTOR'`model'EXTRAL') `GMMdynamicStataoutput`model''
		} // end of loop over aggregate and disaggregated model.
	} // end of foreach loop over the sectors.
*} // end of qui.
log close


capture log close
log using "$datadirfung\WBER system GMM TC lag subs in reduced dfbeta sample.log", replace
*************************************************************************************************************************
* SYSTEMS GMM REDUCED SAMPLE TC LAG SUBSTITUTED IN
*************************************************************************************************************************
foreach sector in education health {
	if "`sector'" == "education" {
		local Sector Education
	}
	else if "`sector'" == "health" {
		local Sector Health
	}
	foreach var in publicexp`sector'FADGDP `sector'TCtotalGDP6 {
		capture drop L`var'
		gen double L`var' = L.`var'
	}
	label variable Lpublicexp`sector'FADGDP "Public `sector' exp. lag"
	label variable L`sector'TCtotalGDP6 "`Sector' TC lag"
}
/* Preserve data and replace TC by its lag. */
preserve
foreach sector in education health {
	foreach type in TC {
		replace `sector'`type'totalGDP6 = L`sector'`type'totalGDP6

		if "`sector'" == "education" {
			local sectorname Education
		}	
		else {
			local sectorname Health
		}	
		label variable `sector'`type'totalGDP6 "`sectorname' `type' t-1"
	}/* end loop over types */
}/* end loop over sectors */

*qui {
	qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"

	foreach sector in education health {
		if "`sector'" == "education" {
			local SECTOR EDUCATION
		}
		else if "`sector'" == "health" {
			local SECTOR HEALTH
		}
		else {
			di as error "sector incorrectly specified"
			exit 198
		} // end of if command specifying sector locals

		/* Only look at disaggregate models: */
		foreach model in DISAGGR {
		
			qui xtreg publicexp`sector'FADGDP ``SECTOR'`model'ENDOG' ``SECTOR'PREDETERM' ``SECTOR'STRICTEXOG' `TIME', fe vce(cluster recipientid)
			local Ncountries`sector' =  e(N_clust) // Run a static model to determine N

			foreach instr in 1 2 3 4 {
				if "`instr'" == "A" {
					local instrendog "."
					local instrpredeterm "."
				}
				else {
					local instrendog = `instr' + 1
					local instrpredeterm `instr'
				}

				local EDUCATIONDISAGGRENDOG educationIPtotalGDP6 educationSPtotalGDP6 educationONMtotalGDP6 supporttoNGOstotalGDP6 tradeGDP 
				local HEALTHDISAGGRENDOG healthIPtotalGDP6 healthSPtotalGDP6 healthONMtotalGDP6 supporttoNGOstotalGDP6 tradeGDP
				local EDUCATIONPREDETERM educationTCtotalGDP6 generaltotalGDP6 othersectoreducGDP6 GDPpercapPPPctthousands intDgrowthGDPpercap /// 
				urbanisation debtPVDikhGDP debtservicepublicLTGDP
				local HEALTHPREDETERM healthTCtotalGDP6 generaltotalGDP6 othersectorhealthGDP6 GDPpercapPPPctthousands intDgrowthGDPpercap /// 
				urbanisation debtPVDikhGDP debtservicepublicLTGDP
				/* I'm moving TC from endogenous to predetermined because TC now refers to the lag */
				
				eststo GMML`SECTOR'`model'`instr': xtabond2 publicexp`sector'FADGDP `LAG`SECTOR'' ``SECTOR'`model'ENDOG' /// 
				``SECTOR'PREDETERM' ``SECTOR'STRICTEXOG' `TIME' if `reducedsample`sector'', /// 
				twostep robust small gmmstyle(publicexp`sector'FADGDP, laglimits(2 `instrendog') collapse split) /// 
				gmmstyle(``SECTOR'`model'ENDOG', laglimits(2 `instrendog') collapse) ///
				gmmstyle(``SECTOR'PREDETERM', laglimits(1 `instrpredeterm') collapse) /// 
				ivstyle(``SECTOR'STRICTEXOG' `TIME', eq(level))
				scalar hansendf = e(hansen_df)
				scalar hansenj = e(hansen)
				scalar sarganp = e(sarganp)
				qui fungstoreresults `sector' GMM GMML`SECTOR'`model'`instr' `LAG`SECTOR'' ``SECTOR'`model'ENDOG' ``SECTOR'PREDETERM' /// 
				``SECTOR'STRICTEXOG'
			} // end of loop over different instrument lag lengths.
			di "REDUCED SAMPLE; SECTOR: `SECTOR'; TYPE OF MODEL: "
			esttab GMML`SECTOR'`model'1 GMML`SECTOR'`model'2 GMML`SECTOR'`model'3 GMML`SECTOR'`model'4, /// 
			keep(`LAG`SECTOR'' ``SECTOR'`model'ENDOG' ``SECTOR'PREDETERM' ``SECTOR'STRICTEXOG') order(`L`SECTOR'`model'') `GMMdynamicStataoutput`model''
		} // end of loop over aggregate and disaggregated model.
	} // end of foreach loop over the sectors.
*} // end of qui.
restore
log close


*******************************************************
* START ANEW TO IDENTIFY HADI OUTLIERS
*******************************************************
capture log close
clear all
set mem 100m
set more off
eststo drop *

/* Use the do-file with the macros: */
include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"
/* Include "programmes" do-file. */ 
include "$datadirfung\WBER programmes for replication.do"
/* Start from the "WBER fung data" dataset. */
use "$datadirfung\WBER fung data" // start from original dataset again.


capture log close
log using "$datadirfung\WBER identifying Hadi outliers.log", replace
*******************************************************
* IDENTIFY HADI OUTLIERS
*******************************************************
/* Follow Roodman (2007, WBER) and identify outliers on the basis of partialled out data. Seems to make more sense. */
foreach sector in education health {
	if "`sector'" == "education" {
		local sectorshort educ
	}
	else if "`sector'" == "health" {
		local sectorshort health
	}
	else {
		di as error "sector incorrectly specified"
		exit 198
	} // end of if command specifying sector locals

	xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'SPtotalGDP6 `sector'TCtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
	othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003, fe vce(robust)
	capture drop `sectorshort'sample
	gen `sectorshort'sample = 1 if e(sample) // fix estimation sample
	
	foreach type in SP TC {
		xtreg `sector'`type'totalGDP6 `sector'IPtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 othersector`sectorshort'GDP6 /// 
		GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003 /// 
		if `sectorshort'sample == 1, fe vce(robust)
		capture drop within_`sectorshort'`type'_res
		predict within_`sectorshort'`type'_res, e
	} // end loop over aid types

	xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 othersector`sectorshort'GDP6 /// 
	GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003 /// 
	if `sectorshort'sample == 1, fe vce(robust)
	capture drop within_`sectorshort'exp_res
	predict within_`sectorshort'exp_res, e

	/* Check that partialled out regression works: */
	xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'SPtotalGDP6 `sector'TCtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
	othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003, fe vce(robust)
	reg within_`sectorshort'exp_res within_`sectorshort'SP_res within_`sectorshort'TC_res, nocons
	/* Identify outliers in the partialled out variables. */
	capture drop `sector'outlier
	hadimvo within_`sectorshort'exp_res within_`sectorshort'SP_res within_`sectorshort'TC_res ///
	if `sectorshort'sample == 1, gen(`sector'outlier) // p(0.01)
	count if `sector'outlier == 1
	di r(N) " outliers in sector `sector' using partialled out SP and TC aid and expenditure"
} // end loop over the two sectors
log close // close log identifying Hadi outliers


capture log close
log using "$datadirfung\WBER Hadi outlier analysis.log", replace
****************************************************
* ANALYSIS OF RESULTS WITHOUT HADI OUTLIERS
****************************************************
qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"
qui include "$datadirfung\WBER programmes for replication.do"
qui {
	foreach sector in education health {
		local counter = 1 // identifies the model, depending on whether outliers are dropped or not.
		if "`sector'" == "education" {
			local SECTOR EDUCATION
			local Sector Education
		}
		else if "`sector'" == "health" {
			local SECTOR HEALTH
			local Sector Health
		}

		/* Disaggregated models. */
		eststo FE`SECTOR'DISAGGR`counter': xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003, fe vce(cluster recipientid)
		qui fungstoreresults `sector' FE FE`SECTOR'DISAGGR`counter++' ``SECTOR'DISAGGR'
		eststo FE`SECTOR'DISAGGR`counter': xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003 if `sector'outlier != 1, fe vce(cluster recipientid)
		qui fungstoreresults `sector' FE FE`SECTOR'DISAGGR`counter++' ``SECTOR'DISAGGR'

	}/* end loop over sectors. */
}/* end qui */
	esttab FEEDUCATIONDISAGGR1 FEEDUCATIONDISAGGR2, /// 
	keep(`EDUCATIONDISAGGR') order(`EDUCAGGRDISAGGR') `OLSFEFDStataoutput' ///
	mtitles("Full sample" "Outliers dropped")

	esttab FEHEALTHDISAGGR1 FEHEALTHDISAGGR2, /// 
	keep(`HEALTHDISAGGR') order(`HEALTHAGGRDISAGGR') `OLSFEFDStataoutput' ///
	mtitles("Full sample" "Outliers dropped")
log close


*******************************************************
* START ANEW TO IDENTIFY BACON OUTLIERS
*******************************************************
capture log close
clear all
set mem 100m
set more off
eststo drop *

/* Use the do-file with the macros: */
qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"
/* Include "programmes" do-file. */ 
qui include "$datadirfung\WBER programmes for replication.do"
/* Start from the "WBER fung data" dataset. */
use "$datadirfung\WBER fung data" // start from original dataset again.


capture log close
log using "$datadirfung\WBER identifying BACON outliers.log", replace
*******************************************************
* IDENTIFY BACON OUTLIERS
*******************************************************
/* As with Hadi, identify outliers on the basis of partialled out data. */
foreach sector in education health {
	if "`sector'" == "education" {
		local sectorshort educ
	}
	else if "`sector'" == "health" {
		local sectorshort health
	}
	else {
		di as error "sector incorrectly specified"
		exit 198
	} // end of if command specifying sector locals

	xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'SPtotalGDP6 `sector'TCtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
	othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003, fe vce(robust)
	capture drop `sectorshort'sample
	gen `sectorshort'sample = 1 if e(sample) // fix estimation sample
	
	foreach type in SP TC {
		xtreg `sector'`type'totalGDP6 `sector'IPtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 othersector`sectorshort'GDP6 /// 
		GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003 /// 
		if `sectorshort'sample == 1, fe vce(robust)
		capture drop within_`sectorshort'`type'_res
		predict within_`sectorshort'`type'_res, e
	} // end loop over aid types

	xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 othersector`sectorshort'GDP6 /// 
	GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003 /// 
	if `sectorshort'sample == 1, fe vce(robust)
	capture drop within_`sectorshort'exp_res
	predict within_`sectorshort'exp_res, e

	/* Check that partialled out regression works: */
	xtreg publicexp`sector'FADGDP `sector'IPtotalGDP6 `sector'SPtotalGDP6 `sector'TCtotalGDP6 `sector'ONMtotalGDP6 generaltotalGDP6 supporttoNGOstotalGDP6 /// 
	othersector`sectorshort'GDP6 GDPpercapPPPctthousands intDgrowthGDPpercap urbanisation tradeGDP debtPVDikhGDP debtservicepublicLTGDP year1991-year2003, fe vce(robust)
	reg within_`sectorshort'exp_res within_`sectorshort'SP_res within_`sectorshort'TC_res, nocons

	/* Identify outliers in the partialled out variables. */
	capture drop `sector'outlier
	bacon within_`sectorshort'exp_res within_`sectorshort'SP_res within_`sectorshort'TC_res ///
	if `sectorshort'sample == 1, gen(`sector'outlier)
	count if `sector'outlier == 1
	di r(N) " outliers in sector `sector' using SP and TC aid and expenditure"
} // end loop over the two sectors
log close // close log identifying bacon outliers


capture log close
log using "$datadirfung\WBER BACON outlier analysis.log", replace
**********************************************************
* ANALYSIS OF RESULTS WITHOUT BACON OUTLIERS
**********************************************************
qui include "C:\Users\Nicolasvds\Documents\My papers\Is foreign aid fungible, education and health\Data\Estimated complete disbursements\regression do-files\WBER replication\WBER macros for replication.do"
qui include "$datadirfung\WBER programmes for replication.do"
qui {
	foreach sector in education health {
		local counter = 1 // identifies the model, depending on which outliers are dropped.
		if "`sector'" == "education" {
			local SECTOR EDUCATION
			local Sector Education
		}
		else if "`sector'" == "health" {
			local SECTOR HEALTH
			local Sector Health
		}

		/* Disaggregated models. */
		eststo FE`SECTOR'DISAGGR`counter': xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003, fe vce(cluster recipientid)
		qui fungstoreresults `sector' FE FE`SECTOR'DISAGGR`counter++' ``SECTOR'DISAGGR'
		eststo FE`SECTOR'DISAGGR`counter': xtreg publicexp`sector'FADGDP ``SECTOR'DISAGGR' year1991-year2003 if `sector'outlier != 1, fe vce(cluster recipientid)
		qui fungstoreresults `sector' FE FE`SECTOR'DISAGGR`counter++' ``SECTOR'DISAGGR'

	}/* end loop over sectors. */
}/* end qui */
	esttab FEEDUCATIONDISAGGR1 FEEDUCATIONDISAGGR2, /// 
	keep(`EDUCATIONDISAGGR') order(`EDUCAGGRDISAGGR') `OLSFEFDStataoutput' ///
	mtitles("Full sample" "Outliers dropped")

	esttab FEHEALTHDISAGGR1 FEHEALTHDISAGGR2, /// 
	keep(`HEALTHDISAGGR') order(`HEALTHAGGRDISAGGR') `OLSFEFDStataoutput' ///
	mtitles("Full sample" "Outliers dropped")
log close
